<template>
  <Headers page="order" />
  <div class="content">
    <el-card>
      <template #header>基本信息</template>
      <el-date-picker
        v-model="form.usedate"
        type="date"
        placeholder="选择日期"
        size="large"
        value-format="YYYY-MM-DD"
        v-if="userStore.sceneDate == '1'"
      />

      <el-radio-group
        v-model="form.ferryid"
        @change="selectFerry"
        class="mpt10"
      >
        <el-radio
          :value="1"
          size="large"
          border
          class="mpb10"
          v-if="userStore.sceneAccess.indexOf('1') !== -1"
        >
          <div>山咀-上川</div>
        </el-radio>
        <el-radio
          :value="2"
          size="large"
          border
          class="mpb10"
          v-if="userStore.sceneAccess.indexOf('1') !== -1"
        >
          <div>山咀-下川</div>
        </el-radio>
        <el-radio
          :value="3"
          size="large"
          border
          class="mpb10"
          v-if="userStore.sceneAccess.indexOf('2') !== -1"
        >
          <div>上川-山咀</div>
        </el-radio>
        <el-radio
          :value="4"
          size="large"
          border
          class="mpb10"
          v-if="userStore.sceneAccess.indexOf('3') !== -1"
        >
          <div>下川-山咀</div>
        </el-radio>
      </el-radio-group>
    </el-card>
    <el-card class="mpt10">
      <template #header>车型信息</template>
      <el-radio-group v-model="form.suitid" @change="selectSuit" class="mpt10">
        <el-radio
          v-for="item in productInfo.suitList"
          :key="item.id"
          :label="item.title"
          :value="item.id"
          size="large"
          border
          class="mpb10"
          style="width: 150px"
        >
          <div>{{ item.title }}</div>
        </el-radio>
      </el-radio-group>

      <el-checkbox
        v-if="limit_driver_num > 0"
        v-model="form.isdriver"
        label="司机跟车"
        size="large"
        border
        class="mpt10"
      />
    </el-card>
    <el-card class="mpt10">
      <template #header>航班信息</template>
      <el-radio-group v-model="form.flightid">
        <template v-for="item in productInfo.flightList">
        <el-radio          
          v-if="Math.floor(item.stock / car_stock_ratio)>=-1"
          :key="item.id"
          :value="item.id"
          size="large"
          border
          class="mpb10"
          :disabled="
            item.stock <= 0 ||
            (form.usedate == todayDate() &&
              Number(item.displayorder) <
                Number(productInfo.suitInfo.flightdisplayorder))
          "
        >
          <div>{{ item.title }}</div>
          <div>车：{{ Math.floor(item.stock / car_stock_ratio) }}</div>
          <div>司：{{ item.dstock }}</div>
        </el-radio>
      </template>
      </el-radio-group>
    </el-card>

    <el-card class="mpt10">
      <template #header>月结用户编码</template>
      <el-input v-model="code" placeholder="请输入月结用户编码"  search  size="large" clearable @clear="clearMerchant">
        <template #append>
        <el-button :icon="Search" @click="remoteMethod(code)"/>
      </template>
      </el-input>

      <el-descriptions direction='vertical' border style="margin-top:10px" v-if="merchant">
        <el-descriptions-item label="商户名称">{{merchant.merchant_name}}</el-descriptions-item>
        <el-descriptions-item label="成员名称">{{merchant.member_name}}</el-descriptions-item>
        <el-descriptions-item label="编码">{{merchant.code}}</el-descriptions-item>       
      </el-descriptions>
    </el-card>

    <el-card class="mpt10" v-if="allow_custom_price == '1'">
      <template #header> 价格 </template>
      <el-input
        v-model="form.customPrice"
        size="large"
        placeholder="请输入价格"
        class="mpt10"
        @change="customPriceChange"
        input-style="color:red;font-size:40px;height:50px"
        @input="form.customPrice = form.customPrice.replace(/[^\d|\.]/g, '')"
        ><template #prefix>
          <span>￥</span>
        </template></el-input
      >
    </el-card>

    <el-card class="mpt10">
      <template #header
        >车辆信息（行驶证识别）

        <el-button-group class="ml-4 fr">
          <el-button :icon="Camera" @click="recognizeCar" />
        </el-button-group>
      </template>
      <el-input
        v-model="form.carnum"
        size="large"
        placeholder="请输入车牌号码"
      />
      <el-card
        header="可选车型"
        class="mpt10"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        v-if="curprice != form.customPrice"
      >
        <el-button
          v-for="item in remarks"
          style="margin-left: 10px; margin-bottom: 10px"
          @click="changeCartype(item)"
          >{{ item }}</el-button
        >
      </el-card>
      <el-input
        v-model="form.cartype"
        size="large"
        placeholder="请输入车型"
        class="mpt10"
      />
      <view
        style="
          display: flex;
          flex-direction: row;
          justify-content: space-between;
        "
      >
        <el-input
          v-model="changdu"
          size="large"
          placeholder="长度"
          class="mpt10"
          @input="computeCarPrice"
          style="width: 150px"
        />
        <view class="mpt10" style="line-height: 40px">X</view>
        <el-input
          v-model="kuandu"
          size="large"
          class="mpt10"
          @input="computeCarPrice"
          placeholder="宽度"
          style="width: 150px"
        />
        <view class="mpt10" style="line-height: 40px">X</view>
        <el-input
          v-model="gaodu"
          size="large"
          class="mpt10"
          @input="computeCarPrice"
          placeholder="高度"
          style="width: 150px"
        />
        <view class="mpt10" style="line-height: 40px">mm</view>
      </view>

      <el-input
        v-if="computerType == 2"
        v-model="form.weight"
        size="large"
        placeholder="请输入车辆重量（吨）"
        class="mpt10"
        @input="computeCarPrice"
      />
    </el-card>
    <el-card class="mpt10" v-if="allow_custom_price == '1'">
      <template #header> 计算规则 </template>
      <el-radio-group
        v-model="computerType"
        @change="selectComputerType"
        class="mpt10"
      >
        <el-radio :value="1" size="large" border class="mpb10">
          <div>长度</div>
        </el-radio>
        <el-radio :value="2" size="large" border class="mpb10">
          <div>重量</div>
        </el-radio>
      </el-radio-group>
    </el-card>

    <el-card class="mpt10" v-if="curprice != form.customPrice">
      <template #header>备注</template>
      <el-card
        header="可选备注"
        class="mpb10"
        style="
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        "
        v-if="curprice != form.customPrice"
      >
        <el-button
          v-for="item in remarks"
          style="margin-left: 10px; margin-bottom: 10px"
          @click="changeRemark(item)"
          >{{ item }}</el-button
        >
      </el-card>
      <el-input v-model="form.remark" size="large" />
    </el-card>
    <el-card class="mpt10">
      <template #header> 联系人电话 </template>
      <el-input
        v-model="form.linktel"
        size="large"
        placeholder="请输入联系人电话"
        class="mpt10"
      />
    </el-card>
    <el-card class="mpt10">
      <template #header>
        车主信息（身份证识别）
        <el-button-group class="ml-4 fr" style="display: flex">
          <el-button :icon="Camera" @click="recognizeIdcard" />

          <el-button :icon="Cellphone" @click="getCardInfo()" />
        </el-button-group>
      </template>
      <el-input
        v-model="form.linkman"
        size="large"
        placeholder="请输入联系人姓名"
      />
      <el-input
        v-model="form.linkIdcard"
        size="large"
        placeholder="请输入联系人身份证号码"
        class="mpt10"
      />
    </el-card>

    

    <el-card class="mpt10">
      <template #header>支付方式</template>
      <el-radio-group v-model="form.paysource" @change="paysourceChange">
        <el-radio v-if="!merchant" value="现金支付" size="large" border class="mpb10"
          >现金支付</el-radio
        >
        <el-radio v-if="!merchant" value="扫码支付" size="large" border class="mpb10"
          >扫码支付</el-radio
        >
        <el-radio
          value="特殊车辆"
          size="large"
          border
          class="mpb10"
          v-if="userStore.specialpay == '1' && !merchant"
          >特殊车辆</el-radio
        >
        <el-radio v-if="merchant" value="月结支付" size="large" border class="mpb10"
          >月结支付</el-radio
        >
      </el-radio-group>
    </el-card>
    <el-card class="mpt10">
      <template #header>付款明细</template>
      <el-row>
        <el-col :span="12">车辆：{{ price }}元</el-col>
        <el-col :span="12" v-if="form.isdriver"
          >司机：{{ driverPrice }}元</el-col
        >
      </el-row>
      <el-row class="mpt10">
        <el-col :span="24" v-if="!form.isdriver"
          >合计：<span class="price">￥{{ price }}</span> 元</el-col
        >
        <el-col :span="24" v-else
          >合计：<span class="price">￥{{ price + driverPrice }}</span>
          元</el-col
        >
      </el-row>
    </el-card>

    

    <el-card class="mpt10 mpb10">
      <el-button
        type="primary"
        plain
        size="large"
        style="width: 100%"
        @click="submit"
        :disabled="btnDisabled"
        >提交订单</el-button
      >
    </el-card>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
import Headers from "@/components/Header.vue";
import request from "@/utils/request";
import { todayDate } from "@/utils/tools";
import { useUser } from "@/stores/user";
import router from "@/router";
import readCard from "@/utils/idcard";
import {
  getcar,
  getidcard,
  creatWS,
  getUploadData,
  clearUploadData,
  closeCap,
} from "@/utils/gpy";
import { ElLoading } from "element-plus";
import { Camera, Cellphone,Search } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";

onMounted(() => {
  form.usedate = todayDate();
  setTimeout(()=>{
    creatWS();  
    },1000)
  
});
onUnmounted(() => {
  closeCap();
});
const merchant = ref(null);
const loading = ref(false);
const code = ref('');
const clearMerchant = ()=>{
  merchant.value = null
}

const remoteMethod = async (query) => {  
  if (query) {
    loading.value = true;
    let params = {
      url: "/scene/info/merchant_info",
      method: "POST",
      data: {
        code: query,
      },
    };
    let res = await request(params);
    loading.value = false
    if(!res.data){
      ElMessageBox.alert('用户不存在或已停用', "提示");
    }
    merchant.value = res.data
  } else {
    merchant.value = null;
  }
};

const userStore = useUser();
const productInfo = reactive({
  suitInfo: {},
  todayPrice: 0,
  suitList: [],
  flightList: [],
  price: 0,
  driverPrice: 0,
});
const computerType = ref(1);
const price = ref(0);
const driverPrice = ref(0);
const limit_driver_num = ref(0);
const needno_car_number = ref(0);
const allow_custom_price = ref(0);
const car_stock_ratio = ref(1);
const btnDisabled = ref(false);
const stock_rule = ref([]);
const price_rule = ref([]);
const weight_price_rule = ref([]);
const size_price_rule = ref([]);
const not_allowed_cartype_keyword = ref([])
const deduct_stock_type = ref("");
const deduct_price_type = ref("");
const within_size = ref(0);
const within_notice = ref("");
const remark = ref("");
const cartype = ref("");
const curprice = ref(0);
const changeRemark = (e) => {
  form.remark = e;
};
const changeCartype = (e) => {
  form.cartype = e;
};
const remarks = ref([]);

const form = reactive({
  ferryid: "",
  usedate: "",
  suitid: "",
  flightid: "",
  isdriver: "",
  carnum: "",
  cartype: "",
  size: "",
  driverName: "",
  driverIdcard: "",
  linkman: "",
  linktel: "",
  linkIdcard: "",
  paysource: "",
  customPrice: "",
  remark: "",
  weight: 0,
});

const changdu = ref("");
const kuandu = ref("");
const gaodu = ref("");

const selectFerry = async (value) => {
  form.suitid = "";
  form.flightid = "";
  form.isdriver = "";
  form.remark = "";
  productInfo.flightList = [];
  productInfo.suitList = [];
  limit_driver_num.value = 0;
  let params = {
    url: "/scene/ferry/get_detail",
    method: "POST",
    data: {
      id: value,
    },
  };
  let res = await request(params);
  if (res.status) {
    productInfo.suitInfo = res.data;
    productInfo.suitList = res.data.suit_list[0].child;
    productInfo.suitList = productInfo.suitList.filter((item) => {
      if (item.need_scene_booking != "1") return item;
    });
  }
};

const selectComputerType = async (value) => {
  if (value == 1) {
    price_rule.value = size_price_rule.value;
  } else {
    price_rule.value = weight_price_rule.value;
  }
  computeCarPrice();
};

const selectSuit = async (value) => {
  let params = {
    url: "/scene/ferry/get_flight",
    method: "POST",
    data: {
      id: form.ferryid,
      usedate: form.usedate,
    },
  };
  let res = await request(params);
  if (res.status) {
    productInfo.flightList = res.data;
    getToDayPrice();
    getRemarks();
    check();
  }
};
const getRemarks = async () => {
  let params = {
    url: "/scene/ferry/get_remark",
    method: "POST",
    data: {},
  };
  let res = await request(params);
  if (res.status) {
    remarks.value = res.data;
  }
};

const getToDayPrice = async () => {
  let params = {
    url: "/scene/ferry/book_suit",
    method: "POST",
    data: {
      ferry_id: form.ferryid,
      suit_id: form.suitid,
      date: form.usedate,
    },
  };
  let res = await request(params);
  if (res.status) {
    productInfo.price = res.data.prices[0].price;
    productInfo.driverPrice = res.data.prices[0].driver_price;
    price.value = productInfo.price;
    driverPrice.value = productInfo.driverPrice;
    limit_driver_num.value = res.data.prices[0].limit_driver_num;
    needno_car_number.value = res.data.prices[0].needno_car_number;
    allow_custom_price.value = res.data.prices[0].allow_custom_price;
    size_price_rule.value = res.data.prices[0].size_price_rule;
    weight_price_rule.value = res.data.prices[0].weight_price_rule;
    if (computerType.value == 1) {
      price_rule.value = size_price_rule.value;
    } else {
      price_rule.value = weight_price_rule.value;
    }
    stock_rule.value = res.data.prices[0].stock_rule;
    car_stock_ratio.value = res.data.prices[0].car_stock_ratio;
    deduct_price_type.value = res.data.prices[0].deduct_price_type;
    deduct_stock_type.value = res.data.prices[0].deduct_stock_type;
    within_size.value = res.data.prices[0].within_size;
    within_notice.value = res.data.prices[0].within_notice;
    not_allowed_cartype_keyword.value = res.data.prices[0].not_allowed_cartype_keyword;
    check();
  }
};

const computeCarPrice = () => {
  let rex = new RegExp(/\d+/g);
  if (changdu.value) {
    form.size = changdu.value;
  }
  if (kuandu.value) {
    form.size += "X" + kuandu.value;
  }
  if (gaodu.value) {
    form.size += "X" + gaodu.value;
  }
  let size = computerType.value == 1 ? form.size.match(rex)[0] : form.weight;
  if (deduct_price_type.value && price_rule.value.length > 0) {
    price_rule.value.forEach((e) => {
      if (e.price > 0 && e.max > 0) {
        if (Number(size) >= Number(e.min) && Number(size) <= Number(e.max)) {
          if (computerType.value == 1) {
            form.customPrice = Math.round(size/1000 * 10)/10 * e.price;
            curprice.value = Math.round(size/1000 * 10)/10 * e.price;
          } else {
            form.customPrice = size * e.price;
            curprice.value = size * e.price;
          }
          customPriceChange();
        }
      }
    });
  }

  if (deduct_stock_type.value && stock_rule.value.length > 0) {
    stock_rule.value.forEach((e) => {
      if (e.stock > 0 && e.max > 0) {
        if (Number(size) >= Number(e.min) && Number(size) <= Number(e.max)) {
          car_stock_ratio.value = e.stock;
        }
      }
    });
  }
};

const customPriceChange = () => {
  price.value = form.customPrice;
};

const getCardInfo = async () => {
  const info = await readCard();
  if (info.data.result == 0) {
    form.linkman = info.data.wzInfo.xm.replace(/^\s+|\s+$/g, "");
    form.linkIdcard = info.data.wzInfo.gmsfhm.replace(/^\s+|\s+$/g, "");
  } else {
    ElMessageBox.alert(info.data.errorMsg, "错误");
  }
};

const paysourceChange = (value) => {
  if (value == "特殊车辆") {
    price.value = 0;
    driverPrice.value = 0;
  } else if (allow_custom_price.value == "1" || price_rule.value.length > 0) {
    price.value = form.customPrice;
  } else {
    price.value = productInfo.price;
    driverPrice.value = productInfo.driverPrice;
  }
};

const check = () => {
  if (form.paysource == "特殊车辆") {
    price.value = 0;
    driverPrice.value = 0;
  } else {
    price.value = productInfo.price;
    driverPrice.value = productInfo.driverPrice;
  }
};

const checkCarnumber = async () => {
  let params = {
    url: "/scene/ferry/check_carnumber",
    method: "POST",
    data: {
      carnumber: form.carnum,
      ferryid: form.ferryid,
    },
  };
  let res = await request(params);
  if (res.status) {
    return res.data;
  }
};

const submit = async () => {
  let cartypeStat=false
  not_allowed_cartype_keyword.value.forEach(item=>{   
    if(form.cartype.includes(item)==true){
      cartypeStat=true
    }
  })
  if(cartypeStat==true){
      ElMessageBox.alert('车型不正确', "提示");
      return;
  }

  let carstatus = await checkCarnumber();
  if (carstatus) {
    let xx = await ElMessageBox.confirm(
      "当天线路订单已存在该车辆，确定继续吗",
      "提示",
      { confirmButtonText: "继续" }
    );
    if (xx != "confirm") {
      return;
    }
  }

  let rex = new RegExp(/\d+/);
  if (
    within_size.value > 0 &&
    form.size.match(rex)[0] > Number(within_size.value)
  ) {
    ElMessageBox.alert(within_notice.value, "提示");
    return;
  }
  let carist = [
    {
      carnumber: form.carnum,
      cartype: form.cartype,
      size: form.size,
    },
  ];
  let tourist;
  if (form.isdriver) {
    tourist = [
      {
        tourername: form.linkman,
        idcard: form.linkIdcard,
        cardtype: "身份证",
      },
    ];
  }
  let book_list = [
    {
      suit_id: form.suitid,
      sku_id: 0,
      num: 1,
      drivernum: form.isdriver ? 1 : 0,
      use_date: form.usedate,
      carist: carist,
      tourist: tourist ?? [],
      flight_id: form.flightid,
    },
  ];
  let params = {
    url: "/scene/ferry/add_order",
    method: "POST",
    data: {
      product_id: form.ferryid,
      linkman: form.linkman,
      linktel: form.linktel,
      linkidcard: form.linkIdcard,
      mobile: form.linktel,
      flight_id: form.flightid,
      source: 9,
      paysource: form.paysource,
      book_list: JSON.stringify(book_list),
      saleman: userStore.userName,
      salemanid: userStore.userId,
      customPrice: form.customPrice,
      remark: form.remark,
      merchant_id:merchant.value?merchant.value.merchant_id:'',
      merchant_member_id:merchant.value?merchant.value.id:'',
      mid:merchant.value?merchant.value.mid:''
    },
  };
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: "订单处理中...",
  });
  btnDisabled.value = true;
  let res = await request(params);
  if (res.status) {
    router.push({
      name: "view",
      params: { orderid: res.data.id },
    });
  } else {
    ElMessageBox.alert(res.msg, "错误");
  }
  btnDisabled.value = false;
  loadingInstance.close();
};

const recognizeCar = async () => {
  getcar();
  let intervalId = setInterval(() => {
    let data = getUploadData();
    console.log(data)
    if (data != "") {
      let arr = data.split("|");
      if (arr.length > 1) {
        let data2 = arr[1].substring(0, arr[0]);
        data2 = JSON.parse(data2);
        if (data2.face) {
          form.carnum = data2.face.licensePlateNumber;
          form.cartype = data2.face.vehicleType;
        }
        if (data2.back) {
          form.size = data2.back.overallDimension;
          let rex = new RegExp(/\d+/g);
          changdu.value = form.size.match(rex)[0];
          kuandu.value = form.size.match(rex)[1];
          gaodu.value = form.size.match(rex)[2];
          computeCarPrice();
        }
        clearUploadData()
      } else {
        ElMessageBox.alert("识别失败，请检查是否放好证件或光线不足", "错误");
        form.carnum = "";
        form.cartype = "";
        form.size = "";
      }
      clearInterval(intervalId);
    }
  }, 500);
};

const recognizeIdcard = async () => {
  getidcard();
  let intervalId = setInterval(() => {
    let data = getUploadData();

    if (data != "") {
      let arr = data.split("|");
      if (arr.length > 1) {
        let data2 = arr[1].substring(0, arr[0]);
        data2 = JSON.parse(data2);
        if (data2.face) {
          form.linkman = data2.face.name;
          form.linkIdcard = data2.face.idNumber;
        }
      } else {
        ElMessageBox.alert("识别失败，请检查是否放好证件或光线不足", "错误");
        form.linkIdcard = "";
        form.linkman = "";
      }
      clearInterval(intervalId);
    }
  }, 500);
};
</script>

<style scoped>
.el-radio {
  height: 70px;
}
.content {
  margin: 20px auto;
  max-width: 600px;

  display: flex;
  flex-direction: column;
  justify-content: center;
}
.mpt10 {
  margin-top: 10px;
}
.mpb10 {
  margin-bottom: 10px;
}
.fr {
  float: right;
}
.price {
  font-size: 20px;
  color: red;
}
</style>